#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    //设置根节点标题
    ui->treeWidget->setHeaderLabels({"动物","小动物"});
    ui->treeWidget->setColumnCount(2);
    //增加顶层节点
    QTreeWidgetItem* item= new QTreeWidgetItem();
    item->setText(0,"猫");
    ui->treeWidget->addTopLevelItem(item);

    QTreeWidgetItem* item_fly = new QTreeWidgetItem();
    item_fly->setText(1,"鸟");
    ui->treeWidget->addTopLevelItem(item_fly);

    QTreeWidgetItem* item2= new QTreeWidgetItem();
    item2->setText(0,"狗");
    ui->treeWidget->addTopLevelItem(item2);


    //增加一些子节点
    QTreeWidgetItem* item4 = new QTreeWidgetItem();
    item4->setText(0,"黑猫");
    item->addChild(item4);

    QTreeWidgetItem* item5= new QTreeWidgetItem();
    item5->setText(0,"白猫");
    item->addChild(item5);

    QTreeWidgetItem* item6 = new QTreeWidgetItem();
    item6->setText(0,"大黄狗");
    item2->addChild(item6);

    QTreeWidgetItem* item7 = new QTreeWidgetItem();
    item7->setText(0,"泰迪");
    item2->addChild(item7);

    QTreeWidgetItem* item8 = new QTreeWidgetItem();
    item8->setText(1,"鹦鹉");
    item_fly->addChild(item8);

    ui->treeWidget->expandAll();
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_addTop_clicked()
{
    // 获取输⼊框内容
     const QString& text = ui->lineEdit->text();
     if (text.isEmpty()) {
     return;
     }
     // 添加到顶层节点中
     QTreeWidgetItem* item = new QTreeWidgetItem();
     item->setText(0, text);
     ui->treeWidget->addTopLevelItem(item);
}

void Widget::on_pushButton_addCom_clicked()
{
    // 获取输⼊框内容
     const QString& text = ui->lineEdit->text();
     if (text.isEmpty()) {
     return;
     }
     // 获取到当前选中的节点
     QTreeWidgetItem* currentItem = ui->treeWidget->currentItem();
     if (currentItem == nullptr) {
     return;
     }
     // 构造新的 item
      QTreeWidgetItem* newItem = new QTreeWidgetItem();
      newItem->setText(0, text);
      // 添加 item 到选中节点
      currentItem->addChild(newItem);
      // 展开⽗节点
      currentItem->setExpanded(true);
}

void Widget::on_pushButton_delete_clicked()
{
    // 获取到当前选中的节点
     QTreeWidgetItem* currentItem = ui->treeWidget->currentItem();
     if (currentItem == nullptr) {
     return;
     }
     // 获取当前节点的⽗节点
     QTreeWidgetItem* parent = currentItem->parent();
     if (parent == nullptr) {
     // 顶层节点
     int index = ui->treeWidget->indexOfTopLevelItem(currentItem);
     ui->treeWidget->takeTopLevelItem(index);
     } else {
     // ⾮顶层节点
     parent->removeChild(currentItem);
     }
}
